<template>
  <HeadContainer class="mine-earn-withdrawal-history bg-background" :title="$t('title.wdrlReq')" @back="back">
    <div class="margin-37 d-flex align-center justify-center">
      <MoneyCard :amount="balance"></MoneyCard>
    </div>
    <div>
      <div class="mt-6 gap-col-16">
        <!-- <div>
          <div @click="toggleOptions()" class="custom-select pointer" ref="customSelectRef">
            <div class="align-center flex-row position-relative">
              <span class="font-size-12 font-style-normal font-weight-400 line-height-120">
                {{ $t('label.earnIndex.withDrawType') }}
              </span>
              <div class="select-wrap" :class="{ 'select-error': withdrawal.type.error }">
                <span :class="{ 'text-white': selectedOption }" class="font-size-14">
                  {{ selectedOption || $t('placeholder.withDrawType') }}
                </span>
                <Icon class="ms-2 arrow" name="arrowDown"></Icon>
              </div>
              <transition name="fade">
                <div v-show="showOptions" class="option">
                  <div
                    class="option-item font-size-14"
                    v-for="(item, index) in withDrawType"
                    :key="index"
                    @click="selectOption(item.value, item.title)"
                  >
                    {{ item.title }}
                  </div>
                </div>
              </transition>
            </div>
          </div>
          <div
            v-if="withdrawal.type.error"
            class="text-end font-size-12 font-weight-400 line-height-120 text-primary-x mt-1"
          >
            {{ withdrawal.type.error }}
          </div>
        </div> -->
        <!-- <InputWrap
          v-model="withdrawal.payee.value"
          :label="$t('label.earnIndex.payee')"
          :placeholder="$t('placeholder.payee')"
          :err-msg="withdrawal.payee.error"
        ></InputWrap> -->
        <!-- <InputWrap
          v-model="withdrawal.bankAccount.value"
          :label="$t('label.earnIndex.bankAccount')"
          :placeholder="$t('placeholder.bankAccount')"
          :err-msg="withdrawal.bankAccount.error"
        ></InputWrap> -->
        <InputWrap
          v-model="withdrawal.amount.value"
          :label="$t('label.earnIndex.withdrawalAmount')"
          :placeholder="$t('placeholder.withdrawalAmount')"
          :err-msg="withdrawal.amount.error"
        ></InputWrap>
        <div style="">
          <ol class="rule">
            <li class="text-subtitle-x font-size-12 font-style-normal line-height-140 font-weight-400">
              {{ $t('content.withdrawRule.first') }}
            </li>
            <li class="text-subtitle-x font-size-12 font-style-normal line-height-140 font-weight-400">
              {{ $t('content.withdrawRule.second') }}
            </li>
            <li class="text-subtitle-x font-size-12 font-style-normal line-height-140 font-weight-400">
              {{ $t('content.withdrawRule.third') }}
            </li>
          </ol>
        </div>
      </div>
      <v-divider class="mt-4"></v-divider>
      <div class="mt-4">
        <div class="d-flex gap-row-16">
          <div @click="onSubmit()" class="primary-btn w-100 d-flex justify-center align-center line-height-140">
            {{ $t('common.apply') }}
          </div>
        </div>
      </div>
      <div v-if="saveErrMsg" class="text-start err-msg font-size-14 font-weight-400 line-height-120 text-primary-x">
        {{ saveErrMsg }}
      </div>
    </div>
  </HeadContainer>
</template>

<script setup>
import { onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useEarnStore } from '@/store/earn'
import { usePopupDialogStore } from '@/store/popup-dialog'
import { usePopupMessageStore } from '@/store/popup-message'
import { $t } from '@/i18n'
import { useYup, validate } from '@/plugins/yup'
import InputWrap from '@/components/form/InputWrap.vue'
import HeadContainer from '@/components/layout/HeadContainer.vue'
import MoneyCard from '@/components/mine/MoneyCard.vue'
import { POPUP_DIALOG_TYPE, WITHDRAW_TYPE } from '@/constant'
import API from '@/http'

const emits = defineEmits(['toPage', 'back'])
const accountStore = useAccountStore()
console.log('=>(MineEarnWdrlReq.vue:105) accountStore', accountStore)

function back() {
  emits('toPage', 2, 'earnings')
  withdrawal.type.value = ''
  withdrawal.type.error = ''
  withdrawal.type.check = false
  withdrawal.payee.value = ''
  withdrawal.payee.error = ''
  withdrawal.payee.check = false
  withdrawal.bankAccount.value = ''
  withdrawal.bankAccount.error = ''
  withdrawal.bankAccount.check = false
  withdrawal.amount.value = ''
  withdrawal.amount.error = ''
  withdrawal.amount.check = false
}

const { open } = usePopupMessageStore()

const earnStore = useEarnStore()
const { refreshBalance } = earnStore
const { balance } = storeToRefs(earnStore)
onMounted(refreshBalance)

// 客製化下拉式選單
const showOptions = ref(false)
const selectedOption = ref(null)
const customSelectRef = ref(null)

const toggleOptions = () => {
  showOptions.value = !showOptions.value
  const iconElement = document.querySelector('.arrow')
  if (iconElement) {
    if (showOptions.value) {
      iconElement.classList.add('rotate')
    } else {
      iconElement.classList.remove('rotate')
    }
  }
}

const handleGlobalClick = (event) => {
  const target = event.target
  const dropdown = customSelectRef.value
  if (showOptions.value && dropdown && !dropdown.contains(target)) {
    toggleOptions()
  }
}

onMounted(() => {
  window.addEventListener('click', handleGlobalClick, true)
})

onBeforeUnmount(() => {
  window.removeEventListener('click', handleGlobalClick, true)
})

const selectOption = (optionValue, optionTitle) => {
  withdrawal.type.value = optionValue
  selectedOption.value = optionTitle
}

const withDrawType = ref([
  // 1:银行卡 5:Paypal 10:其它
  { title: $t('label.earnIndex.bankCard'), value: WITHDRAW_TYPE.BANK_CARD },
  { title: $t('label.earnIndex.paypal'), value: WITHDRAW_TYPE.PAYPAL },
  { title: $t('label.earnIndex.other'), value: WITHDRAW_TYPE.OTHER },
])

const withdrawal = reactive({
  type: {
    value: null,
    error: '',
    check: false,
  },
  payee: {
    value: '',
    error: '',
    check: false,
  },
  bankAccount: {
    value: '',
    error: '',
    check: false,
  },
  amount: {
    value: '',
    error: '',
    check: false,
  },
})

// Select error style
const selectErr = ref(null)
watch(
  () => withdrawal.type.error,
  (newValue) => {
    if (newValue && selectErr.value) {
      selectErr.value.classList.add('select-error')
    } else if (selectErr.value) {
      selectErr.value.classList.remove('select-error')
    }
  },
)
onMounted(() => {
  selectErr.value = document.querySelector('.v-field')
})

const saveErrMsg = ref('')

const yup = useYup()
const schemaType = yup.string().required()
const schemaPayee = yup.string().required().min(2).max(50)
const schemaBankAccount = yup
  .string()
  .matches(/^[0-9]{16}$/, `${$t('yup.number.cardNum')}`)
  .required(`${$t('yup.mixed.required')}`)
const schemaAmount = yup
  .number()
  .required(`${$t('yup.mixed.required')}`)
  .positive()
  .min(20, `${$t('yup.amount.min')}`)
  .typeError(`${$t('yup.number.positive')}`)

const { $popupDialog } = usePopupDialogStore()

const onSubmit = () => {
  const validations = [
    // validate(schemaType, withdrawal.type),
    // validate(schemaPayee, withdrawal.payee),
    // validate(schemaBankAccount, withdrawal.bankAccount),
    validate(schemaAmount, withdrawal.amount),
  ]

  Promise.all(validations).then(() => {
    // withdrawal.payee.check && withdrawal.payee.check && withdrawal.bankAccount.check &&
    if (withdrawal.amount.check) {
      console.log('前端驗證通過')
      $popupDialog(POPUP_DIALOG_TYPE.CONFIRM, {
        title: $t('title.reconfirm'),
        content: $t('content.confirmAmount', { amount: withdrawal.amount.value }),
        confirm: () => saveWithdrawal(),
        cancel: () => {},
        showClose: false,
      }).open()
    } else {
      console.log('前端驗證失敗')
    }
  })
}

const saveWithdrawal = async () => {
  console.log('accountStore.is_kyc', accountStore)
  if (!accountStore.userData.is_kyc) {
    setTimeout(() => {
      $popupDialog(POPUP_DIALOG_TYPE.CONFIRM, {
        title: '請先完成身份驗證',
        content: '為了確保交易安全並防止濫用，您需要完成 KYC（身份驗證）才能提領收益請提交驗證資料，即可解鎖提現功能',
        confirm: () => emits('toPage', 3, 'kyc-verify'),
        cancel: () => {},
        confirmText: '前往驗證',
        showClose: false,
      }).open()
    }, 600)
    return
  }

  try {
    const data = {
      // type: withdrawal.type.value,
      // acount_name: withdrawal.payee.value,
      // card_number: withdrawal.bankAccount.value,
      money: withdrawal.amount.value,
    }
    await API.Withdraw.create({ data })
    await refreshBalance()
    open($t('common.applySuc'))
    back()
    saveErrMsg.value = ''
  } catch (e) {
    saveErrMsg.value = e.message
  }
}
</script>

<style lang="scss" scoped>
.input-wrap {
  display: flex;
  flex-direction: column;
}

::v-deep(.v-field) {
  border-radius: 0.625rem;
  background-color: rgb(var(--v-theme-surface));
  height: 2.5rem;

  &.select-error {
    border: 0.0625rem solid rgb(var(--v-theme-primary-x));
    border-radius: 0.625rem;
    background: linear-gradient(0deg, rgba(235, 0, 27, 0.1) 0%, rgba(235, 0, 27, 0.1) 100%),
      rgb(var(--v-theme-background));
    background-color: rgb(var(--v-theme-surface));
  }
}

::v-deep(.v-field--error) {
  border-radius: 0.625rem;
  border: 0.0625rem solid rgb(var(--v-theme-primary-x));
}

::v-deep(.v-field__field) {
  height: 2.5rem;
}

::v-deep(.v-field__input) {
  padding-top: 0.625rem !important;
  padding-bottom: 0.625rem !important;
  font-size: 0.875rem;

  input {
    color: rgb(var(--v-theme-input));
    font-family: 'PingFang SC';
    font-size: 0.875rem;
    font-style: normal;
    font-weight: 400;
    line-height: 140%;
    letter-spacing: 0.0125rem;

    &::placeholder {
      color: rgb(var(--v-theme-on-surface)) !important;
    }
  }

  .v-select__selection {
    height: 1.25rem;
  }
}

::v-deep(v-field__append-inner) {
  height: 2.5rem !important;

  .v-select__menu-icon {
    padding-top: 0.625rem !important;
    padding-bottom: 0.625rem !important;
  }
}

::v-deep(.v-select .v-field .v-field__input > input) {
  color: rgb(var(--v-theme-on-surface));
}

::v-deep(.v-field--variant-solo-filled .v-field__overlay) {
  background: none;
}

::v-deep(.v-list-item-title) {
  font-size: 14px !important;
}

::v-slotted(.v-select) {
  .v-field.select-error {
    border: 0.0625rem solid rgb(var(--v-theme-primary-x));
    border-radius: 0.625rem;
    background: linear-gradient(0deg, rgba(235, 0, 27, 0.1) 0%, rgba(235, 0, 27, 0.1) 100%),
      rgb(var(--v-theme-background));
    background-color: rgb(var(--v-theme-surface));
  }
}

.select-wrap {
  display: flex;
  padding: 0.625rem 1rem;
  align-items: center;
  justify-content: space-between;
  border-radius: 0.625rem;
  background-color: rgb(var(--v-theme-surface));
  height: 2.5rem;
  color: rgb(var(--v-theme-input));
  font-family: 'PingFang SC';
  font-size: 0.875rem;
  font-style: normal;
  font-weight: 400;
  line-height: 140%;
  letter-spacing: 0.0125rem;
}

.option {
  position: absolute;
  width: -webkit-fill-available;
  top: 100%;
  left: 0;
  z-index: 1;
  background: rgb(var(--v-theme-surface));
  border-radius: 0.25rem;
  overflow: auto;
  padding: 0.25rem 0;
  box-shadow: 0px 5px 5px -3px var(--v-shadow-key-umbra-opacity, rgba(0, 0, 0, 0.2)),
    0px 8px 10px 1px var(--v-shadow-key-penumbra-opacity, rgba(0, 0, 0, 0.14)),
    0px 3px 14px 2px var(--v-shadow-key-penumbra-opacity, rgba(0, 0, 0, 0.12));

  & .option-item {
    background: rgb(var(--v-theme-surface));
    padding: 0.25rem 1rem;
    color: rgb(var(--v-theme-on-surface));
    cursor: pointer;
    transition: background-color 0.3s;

    &:last-child {
      border-bottom: none;
    }
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.fade-enter-to,
.fade-leave-from {
  opacity: 1;
}

.arrow {
  transition: transform 0.3s;
}

.arrow.rotate {
  transform: rotate(180deg);
}

.select-error {
  border: 0.0625rem solid rgb(var(--v-theme-primary-x));
  border-radius: 0.625rem;
  background: linear-gradient(0deg, rgba(235, 0, 27, 0.1) 0%, rgba(235, 0, 27, 0.1) 100%),
    rgb(var(--v-theme-background));
  background-color: rgb(var(--v-theme-surface));
}

.rule {
  list-style-type: decimal;
  list-style-position: inside;
}
</style>
